import { Module } from '@nestjs/common';
import { WinstonModule, WinstonModuleOptions } from 'nest-winston';
import { ConfigService } from '@nestjs/config';
import * as winston from 'winston';
import { Console } from 'winston/lib/winston/transports';
import * as DailyRotateFile from 'winston-daily-rotate-file';
import { LogEnum } from 'src/enum/config.enum';

@Module({
  imports: [
    WinstonModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => {
        function createDailyRotateTrasnport(level: string, filename: string) {
          return new DailyRotateFile({
            datePattern: 'YYYY-MM-DD-HH',
            zippedArchive: true,
            filename: `${filename}-%DATE%.log`,
            dirname: 'logs',
            maxFiles: '14d',
            maxSize: '20m',
            level,
            format: winston.format.combine(
              winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
              winston.format.printf(({ level, message, timestamp }) => {
                return `${timestamp} [${level}]: ${message}`;
              }),
            ),
          });
        }
        const consoleTransports = new Console({
          level: configService.get(LogEnum.LOG_LEVEL),
          format: winston.format.combine(
            winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
            winston.format.printf(({ level, message, timestamp }) => {
              return `${timestamp} [${level}]: ${message}`;
            }),
          ),
        });

        return {
          transports: [
            consoleTransports,
            createDailyRotateTrasnport('info', 'application'),
            createDailyRotateTrasnport('warn', 'error'),
          ],
        } as WinstonModuleOptions;
      },
    }),
  ],
  controllers: [],
  providers: [],
})
export class LoggerModule {}
